#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2021/6/8
# @Author    :zhangxuchuo
# @Email     :zhangxuchuo@bbdservice.com
# @File      :IC107_Ind12MonsContiOvduCnt
# @Software  :PyCharm


'''eof
name:申请人近12个月贷款、贷记卡记准贷记卡连续逾期期数最大值
code:IC107_Ind12MonsContiOvduCnt
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import re
import sys
import datetime
import pandas as pd

# reload(sys)
# sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--', []]


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
    '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def isFloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date

# 贷款单账户12个月内连续逾期次数：
# od_mon_list = [0]
# 1. 只保留账户类型为贷款的账户：IF 基本信息段(PD01A)·账户类型(PD01AD01) IN [D1 (非循环贷账户), R1 (循环贷账户), R4 (循环额度下分账户)]，保留
# 2. 对该账户，od_mon = COUNT(历史表现信息(PD01EH)·月份(PD01ER03)  | 历史表现信息(PD01EH)·月份(PD01ER03)距今12个月以内的 历史表现信息(PD01EH)·还款状态(PD01ED01) 取值为["1", …, "7"]形成字符串，获取都为数字的字符串，获取最长数字字符串的长度作为最长连续逾期次数
#
#
# 贷记卡单账户12个月内连续逾期次数：
# od_mon_list = [0]
# 1. 只保留账户类型为贷记卡的账户：IF 基本信息段(PD01A)·账户类型(PD01AD01) == R2(贷记卡账户)]，保留
# 2. 对该账户，od_mon = COUNT(历史表现信息(PD01EH)·月份(PD01ER03)  | 历史表现信息(PD01EH)·月份(PD01ER03)距今12个月以内的 历史表现信息(PD01EH)·还款状态(PD01ED01) 取值为["1", …, "7"]形成字符串，获取都为数字的字符串，获取最长数字字符串的长度作为最长连续逾期次数
#
# 准贷记卡单账户12个月内连续逾期次数：
# od_mon_list = [0]
# 1. 只保留账户类型为准贷记卡的账户：IF 基本信息段(PD01A)·账户类型(PD01AD01) == R3(准贷记卡账户)]，保留
# 2. 对该账户，od_mon = COUNT(历史表现信息(PD01EH)·月份(PD01ER03)  | 历史表现信息(PD01EH)·月份(PD01ER03)距今12个月以内的 历史表现信息(PD01EH)·还款状态(PD01ED01) 取值为["3", …, "7"]形成字符串，获取都为数字的字符串，获取最长数字字符串的长度作为最长连续逾期次数
#
# Factor={贷款单账户12个月内连续逾期次数：factor1,贷记卡单账户12个月内连续逾期次数:factor2,
# 准贷记卡单账户12个月内连续逾期次数:factor3}
# return sum (Factor) [不排除后台实现]

def IC107_Ind12MonsContiOvduCnt():
    pat = re.compile('\d+')
    data = IC_DSJ_2D.get('data')
    #PDA 借贷账户信息 [1..1]
    PDA = getTable(data, 'PDA', 1, 0)
    factor1 = [0]
    factor2 = [0]
    factor3 = [0]
    res1 = []
    res2 = []
    res3 = []
    if PDA == [{}]:
        return '缺失值'
    elif PDA == 0:
        return 0
    else:
        #PD01 借贷账户信息单元 [0..*]
        PD01 = getTable(PDA[0], 'PD01', 0, 0)
        if PD01 == [{}]:
            return '缺失值'
        elif PD01 == 0:
            return 0
        else:
            for i in PD01:
                #PD01A 基本信息段 [1..1]
                PD01A = getTable(i, 'PD01A', 1, 1)
                if PD01A == [{}] or PD01A == 0:
                    pass
                else:
                    # PD01AD01 账户类型
                    PD01AD01 = PD01A[0].get('PD01AD01')
                    if PD01AD01 not in null_type_list and PD01AD01 in ['D1', 'R1', 'R4']:
                        #PD01E 最近 5 年内历史表现信息段 [0..1]
                        PD01E = getTable(i, 'PD01E', 0, 1)
                        str = ''
                        if PD01E == [{}] or PD01E == 0:
                            pass
                        else:
                            # PD01EH 历史表现信息 [1.60]
                            PD01EH = getTable(PD01E[0], 'PD01EH', 1, 1)
                            if PD01EH == [{}] or PD01EH == 0:
                                pass
                            else:
                                for j in PD01EH:
                                    # PD01ER03 月份
                                    PD01ER03 = j.get('PD01ER03')
                                    # PD01ED01 还款状态
                                    PD01ED01 = j.get('PD01ED01')
                                    last = (datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=12)).strftime("%Y%m%d")
                                    now = datetime.datetime.now().strftime('%Y%m%d')
                                    if PD01ED01 not in null_type_list and Formate(PD01ER03):
                                        if PD01ED01 != '0' and int(last[:6]) <= int(PD01ER03.replace('-', '')) <= int(now[:6]):
                                            str = str + PD01ED01
                                            res1.append(0)
                                        else:
                                            res1.append(0)
                                    else:
                                        res1.append('缺失值')
                        res = pat.findall(str)
                        lenths = [len(i) for i in res]
                        if lenths:
                            factor1.append(max(lenths))

                    if PD01AD01 not in null_type_list and PD01AD01 in ['R2']:
                        #PD01E 最近 5 年内历史表现信息段 [0..1]
                        PD01E = getTable(i, 'PD01E', 0, 1)
                        str = ''
                        if PD01E == [{}] or PD01E == 0:
                            pass
                        else:
                            # PD01EH 历史表现信息 [1.60]
                            PD01EH = getTable(PD01E[0], 'PD01EH', 1, 1)
                            if PD01EH == [{}] or PD01EH == 0:
                                pass
                            else:
                                for j in PD01EH:
                                    # PD01ER03 月份
                                    PD01ER03 = j.get('PD01ER03')
                                    # PD01ED01 还款状态
                                    PD01ED01 = j.get('PD01ED01')
                                    last = (datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=12)).strftime("%Y%m%d")
                                    now = datetime.datetime.now().strftime('%Y%m%d')
                                    if PD01ED01 not in null_type_list and  Formate(PD01ER03):
                                        if PD01ED01 != '0' and int(last[:6]) <= int(PD01ER03.replace('-', '')) <= int(now[:6]):
                                            str = str + PD01ED01
                                            res2.append(0)
                                        else:
                                            res2.append(0)
                                    else:
                                        res2.append('缺失值')
                        res = pat.findall(str)
                        lenths = [len(i) for i in res]
                        if lenths:
                            factor2.append(max(lenths))

                    if PD01AD01 not in null_type_list and PD01AD01 in ['R3']:
                        #PD01E 最近 5 年内历史表现信息段 [0..1]
                        str = ''
                        PD01E = getTable(i, 'PD01E', 0, 1)
                        if PD01E == [{}] or PD01E == 0:
                            pass
                        else:
                            # PD01EH 历史表现信息 [1.60]
                            PD01EH = getTable(PD01E[0], 'PD01EH', 1, 1)
                            if PD01EH == [{}] or PD01EH == 0:
                                pass
                            else:
                                for j in PD01EH:
                                    # PD01ER03 月份
                                    PD01ER03 = j.get('PD01ER03')
                                    # PD01ED01 还款状态
                                    PD01ED01 = j.get('PD01ED01')
                                    last = (datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=12)).strftime("%Y%m%d")
                                    now = datetime.datetime.now().strftime('%Y%m%d')
                                    if PD01ED01 not in null_type_list and Formate(PD01ER03):
                                        if PD01ED01 not in ['0', '1', '2'] and int(last[:6]) <= int(PD01ER03.replace('-', '')) <= int(now[:6]):
                                            str = str + PD01ED01
                                            res3.append(0)
                                        else:
                                            res3.append(0)
                                    else:
                                        res3.append('缺失值')
                        res = pat.findall(str)
                        lenths = [len(i) for i in res]
                        if lenths:
                            factor3.append(max(lenths))

    if (len(list(set(res1))) == 1 and list(set(res1))[0] == '缺失值') and (len(list(set(res2))) == 1 and list(set(res2))[0] == '缺失值') and (len(list(set(res3))) == 1 and list(set(res3))[0] == '缺失值'):
        return '缺失值'
    else:
        return max([max(factor1), max(factor2), max(factor3)])




# if __name__ == '__main__':
#     with open(r'C:\Users\zdr\Desktop\samples\IC_DSJ_2D.json', encoding='utf8') as ff:
#         dd = json.loads(ff.read())
#     IC_DSJ_2D = dd
#     result = IC107_Ind12MonsContiOvduCnt()
#     print(result)
result = IC107_Ind12MonsContiOvduCnt()
